package com.hdmp.auth.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hdmp.auth.aspect.SysLog;
import com.hdmp.auth.entity.SysPermissionEntity;
import com.hdmp.auth.entity.SysRoleEntity;
import com.hdmp.auth.entity.SysUserEntity;
import com.hdmp.auth.entity.SysUserRoleEntity;
import com.hdmp.auth.mapper.SysUserMapper;
import com.hdmp.auth.util.PasswordHelper;
import com.hdmp.auth.vo.PermissionInfo;
import com.hdmp.auth.vo.ViewUserInfo;
import com.hdmp.mybatis.aspect.annotation.HdDataSource;
import com.hdmp.mybatis.constant.DataSourceEnum;
import com.hdmp.tool.util.BeanUtils;
import com.hdmp.tool.util.LambdaTool;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;


/**
 * @author BigFan
 * @create 2018/11/15 10:27 AM
 */
@Service
public class SysUserService extends ServiceImpl<SysUserMapper, SysUserEntity> {

    @Autowired
    @Lazy
    SysUserMapper sysUserMapper;
    @Autowired
    SysUserRoleService userRoleService;
    @Autowired
    SysRolePermissionService rolePermissionService;

    @Autowired
    @Lazy
    DataAuthService dataAuthService;


    @SysLog(title = "通过用户名查询")
    public SysUserEntity queryByName(String username) {
        if (StringUtils.isEmpty(username)) {
            return null;
        }
        QueryWrapper wrapper = new QueryWrapper();
        Map<String, Object> queryMap = Maps.newHashMap();
        queryMap.put("username", username);
        wrapper.allEq(queryMap, false);
        SysUserEntity userEntity = sysUserMapper.selectOne(wrapper);
        return userEntity;
    }

    @SysLog(title = "通过绑定号")
    public List<SysUserEntity> queryByDztm(String dztm) {
        if (StringUtils.isEmpty(dztm)) {
            return null;
        }
        QueryWrapper wrapper = new QueryWrapper();
        Map<String, Object> queryMap = Maps.newHashMap();
        queryMap.put("dztm", dztm);
        wrapper.allEq(queryMap, false);
        List<SysUserEntity> list = sysUserMapper.selectList(wrapper);

        return list;
    }

    @SysLog(title = "用户查询")
    @HdDataSource(DataSourceEnum.SLAVE)
    public List<SysUserEntity> multiQueryUser(SysUserEntity userEntity, Map<String, String> map) {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.apply(dataAuthService.createDataSql());
        List<SysUserEntity> list = sysUserMapper.selectList(queryWrapper);
        return list;


    }

    public Page<SysUserEntity> multiQuery(Map<String, Object> map, Page<SysUserEntity> page) {
        page.setRecords(sysUserMapper.query(page, map));
        return page;
    }


    /**
     * 根据id获取userEntity
     *
     * @param dbid
     * @return
     */
    public SysUserEntity loadByBdid(Integer dbid) {

        SysUserEntity sysUserEntity = sysUserMapper.selectById(dbid);
        return sysUserEntity == null ? new SysUserEntity() : sysUserEntity;
    }

    public List<SysUserEntity> query() {
        List<SysUserEntity> list = sysUserMapper.selectList(null);
        return list;
    }



    public boolean saveOrUpdate(SysUserEntity userEntity) {

        if(userEntity.getDbid() == null){
            PasswordHelper passwordHelper = new PasswordHelper();
            passwordHelper.encrptPassword(userEntity);
        }else{
            SysUserEntity info = sysUserMapper.selectById(userEntity.getDbid());
            if(!info.getPassword().equals(userEntity.getPassword())) {
                PasswordHelper passwordHelper = new PasswordHelper();
                passwordHelper.encrptPassword(userEntity);
            }
        }

        super.saveOrUpdate(userEntity);
        if (userEntity.getDelRoles() != null && userEntity.getDelRoles().size() > 0) {
            userRoleService.deleteUserRoles(userEntity.getDbid(), userEntity.getDelRoles());
        }
        if (userEntity.getAddRoles() != null && userEntity.getAddRoles().size() > 0) {
            List<SysUserRoleEntity> userRoleEntityList = Lists.newArrayList();
            for (Integer roleId : userEntity.getAddRoles()) {
                SysUserRoleEntity userRoleEntity = new SysUserRoleEntity();
                userRoleEntity.setUserDbid(userEntity.getDbid());
                userRoleEntity.setRoleDbid(roleId);
                userRoleEntityList.add(userRoleEntity);
            }
            userRoleService.saveBatch(userRoleEntityList);
        }
        return true;
    }

    /**
     *根据用户名，获取用户vo
     * @param username
     * @return
     */
    public ViewUserInfo getUserInfo(String username){
        SysUserEntity sysUserEntity = queryByName(username);
        ViewUserInfo viewUserInfo = initUserInfo(sysUserEntity);
        return viewUserInfo;
    }

    /**
     * 初始化 viewUserInfo的相关信息
     *
     * @param sysUserEntity
     * @return
     */
    private ViewUserInfo initUserInfo(SysUserEntity sysUserEntity){
        ViewUserInfo viewUserInfo = new ViewUserInfo();
        BeanUtils.copy(sysUserEntity, viewUserInfo);
        Map<String, PermissionInfo> all_menu;

        Set<PermissionInfo> menus =new HashSet<>();        //所有的菜单
        List<PermissionInfo> opt_permission;
        List<SysRoleEntity> roleEntities = userRoleService.queryStaffRoles(sysUserEntity.getDbid());

        List<SysRoleEntity> roleInfos = roleEntities.stream().map(e -> BeanUtils.copy(e, SysRoleEntity.class)).collect(Collectors.toList());
        viewUserInfo.setRoleInfos(roleInfos);

        List<SysPermissionEntity> user_permission = rolePermissionService.findPermissionEntityByUser(sysUserEntity); //获取用户的所有权限
        System.out.println("-----------------------");
        System.out.println(user_permission);
        System.out.println("-----------------------");
        user_permission = user_permission == null ? Lists.newArrayList() : user_permission;
        List<PermissionInfo> permissionInfos = user_permission.stream().map(e -> BeanUtils.copy(e, PermissionInfo.class)).collect(Collectors.toList());                 // 将实体的信息进行复制，复制到vo表中

        List<String> roleSet = roleEntities.stream().map(c -> c.getCode()).collect(Collectors.toList());
        viewUserInfo.setRoles(roleSet);

        all_menu = permissionInfos.stream().filter(e -> e.getType().equals("00")&&e.getIsDisplay()).collect(Collectors.toMap(e -> e.getDbid() + "", p -> p));   //获取所有menue map;
        all_menu.entrySet().stream().sorted();
        opt_permission = permissionInfos.stream().filter(e -> e.getType().equals("01")).collect(Collectors.toList());                              //按钮显示权限 列表
        Iterator<String> iterator = all_menu.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            PermissionInfo v = all_menu.get(key);
            System.out.println(v);
            System.out.println(v.getDbid()+"::::"+v.getParentId());
            if (v.getParentId() > 0) {
                PermissionInfo parentMenu = all_menu.get(v.getParentId() + "");
                Set<PermissionInfo> children = parentMenu.getPermissionInfos() == null ? new TreeSet<>() : parentMenu.getPermissionInfos();
                children.add(v);
                parentMenu.setPermissionInfos(children);
            } else {
                menus.add(v);
            }
            System.out.println("==============================");
            System.out.println(menus);
            System.out.println("==============================");
        }
        LambdaTool tool = new LambdaTool();
        List<PermissionInfo> distPermissiones = opt_permission.stream().filter(tool.distinctByKey(PermissionInfo::getDbid)).collect(Collectors.toList());

        viewUserInfo.setMenues(menus);
        viewUserInfo.setPermissionInfos(distPermissiones);

        return viewUserInfo;
    }

    public boolean validPassword(Long userid,String password){
        SysUserEntity userEntity=sysUserMapper.selectById(userid);
        String password_1=userEntity.getPassword();
        PasswordHelper passwordHelper = new PasswordHelper();
        userEntity.setPassword(password);
        passwordHelper.encrptPassword(userEntity);
        String password_2=userEntity.getPassword();
        return password_1.equals(password_2)?true:false;
    }

    public void saveNewPassword(Long userid, String password){
        SysUserEntity userEntity=sysUserMapper.selectById(userid);
        userEntity.setPassword(password);
        this.saveOrUpdate(userEntity);
    }
}
